<template>
  <div>
    <!-- 面包屑导航 -->
    <div class="center-w">
      <div class="head">
        <div class="title">身份管理</div>
        <el-button type="primary" @click="addUser">添加身份</el-button>
      </div>
      <el-table :data="tableData">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="身份名"> </el-table-column>
        <el-table-column prop="roleName" label="是否开启月结">
          <template slot-scope="scope">
            <el-switch
              :disabled="scope.row.isDisable"
              @change="monthlySettlement(scope.row)"
              v-model="scope.row.state"
            ></el-switch>
            <span style="margin-left: 10px;">{{
              scope.row.state ? "开" : "关"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="是否开启预约">
          <template slot-scope="scope">
            <el-switch
              @change="uploadAppointStatus(scope.row)"
              v-model="scope.row.appointmentStatus"
            ></el-switch>
            <span style="margin-left: 10px;">{{
              scope.row.appointmentStatus == 1 ? "开" : "关"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column width="180" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row, 1)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="currentTitle"
      :visible.sync="centerDialogVisible"
      width="50%"
    >
      <div class="w">
        <div style="display: flex; margin-bottom: 10px; align-items: center;">
          <div class="prices-s">身份名：</div>
          <el-input
            style="width: 150px;"
            v-model="addList.roleName"
            placeholder="请输入身份名"
          ></el-input>
        </div>
        <div style="display: flex">
          <div class="prices">商品价：</div>
          <el-table border size="mini" :data="addList.perList">
            <el-table-column type="index" align="center"> </el-table-column>
            <el-table-column
              prop="cName"
              width="280"
              align="center"
              label="项目"
            >
              <template slot-scope="scope">
                <span>
                  {{ scope.$index == 0 ? "额外项目" : "检查项目" }}：</span
                >
                <el-input
                  style="width: 180px;"
                  show-word-limit
                  placeholder="请输入"
                  v-model="scope.row.cName"
                  clearable
                  disabled
                  size="mini"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="cPrice" align="center" label="项目金额">
              <template slot-scope="scope">
                <el-input
                  style="width: 80px;"
                  show-word-limit
                  oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  @blur="scope.row.cPrice = $event.target.value"
                  placeholder="请输入"
                  v-model="scope.row.cPrice"
                  size="mini"
                  clearable
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="profit"
              align="center"
              width="240"
              label="佣金比例（分销商身份设置才有效）"
            >
              <template slot-scope="scope">
                <el-input
                  style="width: 80px;"
                  show-word-limit
                  type="number"
                  oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  @blur="scope.row.profit = Number($event.target.value)"
                  placeholder="请输入"
                  v-model="scope.row.profit"
                  size="mini"
                  clearable
                  :disabled="scope.row.cId == 1 || scope.row.cId == 10"
                ></el-input>
                %
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subUpdateRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserRoleList } from "../../api/user";
import { getGoodsList } from "../../api/goods";
import {
  getRoleForDetail,
  updateRole,
  addRole,
  deleteRole,
  roleUpdateState,
  roleUpdateAppointmentStatus
} from "../../api/role";

export default {
  data() {
    return {
      tableData: [],
      centerDialogVisible: false,
      myName: "",
      pageparm: {
        pageIndex: 1,
        size: 10,
        total: 0
      },
      name: "",
      currentTitle: "",
      addList: {},
      projectObj: {}
    };
  },

  created() {
    this._getUserRoleList();
  },
  methods: {
    // 是否开启月结功能
    monthlySettlement(r) {
      this.$confirm(
        `确定${!r.state ? "关闭" : "开启"}月结功能吗？`,
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(() => {
          const params = {
            id: r.id,
            state: r.state
          };
          roleUpdateState(params).then(res => {
            if (res.code == 200) {
              this.$message.success("切换成功!");
            } else {
              this.$message.info("切换失败!");
            }
            this._getUserRoleList();
          });
        })
        .catch(action => {
          this.$message.info("已取消");
          this._getUserRoleList();
        });
    },

    // 是否开启预约功能
    uploadAppointStatus(r) {
      let appointStatus = null;
      appointStatus = r.appointmentStatus ? 1 : 0;
      this.$confirm(
        `确定${!r.appointmentStatus ? "关闭" : "开启"}预约功能吗？`,
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(() => {
          const params = {
            id: r.id,
            state: appointStatus
          };
          roleUpdateAppointmentStatus(params).then(res => {
            if (res.code == 200) {
              this.$message.success("切换成功!");
            } else {
              this.$message.info("切换失败!");
            }
            this._getUserRoleList();
          });
        })
        .catch(action => {
          this._getUserRoleList();
        });
    },

    //获取编辑时候商品列表回显
    _getRoleForDetail(roleId) {
      getRoleForDetail({ roleId }).then(res => {
        if (res.data) {
          this.addList = res.data;
          let list = res.data.perList;
          let obj = {};
          list.forEach(item => {
            item.profit = this.setProfit(2, item.cId, item.profit);
          });
          //把加急拿出来放在第一位显示
          for (let i = 0; i < list.length; i++) {
            if (list[i].cId == 10) {
              obj = list[i];
              list.splice(i, 1);
              break;
            }
          }
          list.unshift(obj);
          this.$nextTick(() => {
            this.addList.perList = list;
          });
        }
      });
    },

    //编辑身份提交
    subUpdateRole() {
      if (this.addList.roleName == "")
        return this.$message.error("身份名不能为空!");
      let x = this.addList.perList.find(v => {
        return v.cPrice === "";
      });
      if (x) return this.$message.error("编辑项价格不能为空!");
      if (this.myName) {
        //编辑
        updateRole(this.addList).then(res => {
          if (res.code == 200) {
            this.$message.success("编辑成功!");
            this.centerDialogVisible = false;
            this._getUserRoleList();
          } else {
            this.$message.error("编辑失败!");
            this.centerDialogVisible = false;
            this._getUserRoleList();
          }
        });
      } else {
        //添加
        addRole(this.addList).then(res => {
          if (res.code == 200) {
            this.$message.success("新增成功!");
            this.centerDialogVisible = false;
            this._getUserRoleList();
          } else {
            this.$message.error("新增失败!");
            this.centerDialogVisible = false;
            this._getUserRoleList();
          }
        });
      }
    },

    //获取角色身份列表
    async _getUserRoleList() {
      const res = await getUserRoleList();
      if (res.data) {
        //过滤掉普通用户 id = 0
        this.tableData = res.data.filter(v => {
          return v.id != 0;
        });

        //斯贝达 和 元电 默认是开启月结方式，且不可以修改。
        this.tableData.forEach(element => {
          if (element.roleName == "斯贝达" || element.roleName == "环亚元电") {
            element.isDisable = true;
          }
          element.appointmentStatus =
            element.appointmentStatus == 1 ? true : false;
        });
        this.pageparm.total = this.tableData.length;
      }
    },

    //获取添加身份时详情里面商品信息回显
    _getGoodsList() {
      getGoodsList().then(res => {
        let list = res.data;
        let arr = [];
        if (list.length > 0) {
          list.map(el => {
            arr.push({
              cName: el.name,
              cPrice: el.price,
              cId: el.id,
              profit: this.setProfit(1, el.id, el.profit)
            });
          });
          let obj = {
            roleName: "",
            perList: arr
          };
          this.addList = obj;
        }
      });
    },

    //特殊项目佣金设置为0
    setProfit(type, id, profit) {
      if (type == 1) {
        //添加身份
        if (id == 1 || id == 10) {
          return 0;
        } else if (id == 11) {
          return 30;
        } else {
          return 10;
        }
      } else {
        //编辑身份
        if (id == 1 || id == 10) {
          return 0;
        }else {
          return profit;
        }
      }
    },

    //编辑弹出弹框
    handleEdit(item) {
      this.centerDialogVisible = true;
      this.currentTitle = "身份编辑";
      this.myName = item.roleName;
      this._getRoleForDetail(item.id);
    },

    //删除
    handleDelete(e) {
      this.$confirm("确定删除吗？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定删除",
        cancelButtonText: "取消"
      })
        .then(() => {
          deleteRole({ roleId: e.id }).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this._getUserRoleList();
            } else {
              this.$message.error("删除失败");
              this._getUserRoleList();
            }
          });
        })
        .catch(action => {
          this.$message.info("取消删除");
        });
    },

    //添加身份
    addUser() {
      this.centerDialogVisible = true;
      this.addList.roleName = "";
      this.myName = "";
      this.currentTitle = "添加身份";
      this._getGoodsList();
    }
  }
};
</script>

<style lang="less" scoped>
.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 85vh;
  padding: 20px;
  border: 1px solid #ccc;
  margin: 20px;
}

.title {
  color: rgba(16, 16, 16, 1);
  font-size: 20px;
  margin-bottom: 10px;
}

.active {
  color: rgb(124, 134, 244) !important;
}

.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.el-input {
  max-width: 200px;
}

// .w {
//   overflow-y: scroll;
//   height: 700px;
// }

.sex {
  display: flex;
  align-items: center;
  align-items: center;
  // margin: 10px 20px 20px 0;
}

.list-w {
  display: flex;
  align-items: center;
}

.sex div {
  color: rgba(109, 109, 109, 1);
  font-size: 16px;
  font-weight: 500;
}

.sex div:first-child {
  max-width: 80px;
  text-align: right;
}

.prices {
  color: rgba(109, 109, 109, 1);
  font-size: 16px;
  font-weight: 700;
  margin-top: 20px;
  width: 100px;
  text-align: right;
}

.prices-s {
  color: rgba(109, 109, 109, 1);
  font-size: 16px;
  font-weight: 700;
  width: 100px;
  text-align: right;
}
</style>
